<template>
  <div>
    <!-- 当点击 取消按钮 时，关闭弹窗 -->
    <el-drawer
      :title="title"
      :visible.sync="visible"
      width="80%"
      top="4vh"
      class="print-model"
      :append-to-body="true"
      @close="clearDialog()"
      v-loading="loding"
      :wrapperClosable="false"
      size="60%"
      :close-on-click-modal="false"
    >
      <div class="pack">
        <ele-form v-model="dialogfrom" v-bind="formConfig" ref="form"></ele-form>

        <div slot="footer" class="dialog-footer demo-drawer__footer">
          <el-button @click="clearDialog()">{{ $t('common.cancel') }}</el-button>
          <!-- <el-button
        type="primary"
        v-if="barcodeInfo.isCreateBarcode != 1"
        @click="creatBoxCode()"
        >生 成
      </el-button> -->
          <!-- <el-button type="danger" v-else @click="clearBoxcode()">清 除 </el-button> -->
          <el-button type="primary" @click="printBoxcode()">{{ $t('common.print') }} </el-button>

          <!-- <el-button
            class="dis-none"
            type="primary"
            v-print="print"
            id="printBtn"
            ref="printBtn"
          /> -->
        </div>
      </div>
    </el-drawer>

    <templateSelect
      ref="templateSelect"
      v-model="dialogfrom.barcodePrintTempCode"
      :searchData="{
        goodsCode: this.dialogfrom.prodCode,
        businessTypeCode: 'PRINT_MES_PC_MATERIAL_CARD'
      }"
      @select="
        (data) => {
          dialogfrom.barcodePrintTemp = data.name
        }
      "
    ></templateSelect>
  </div>
</template>
<script>
import templateSelect from '@/components/templateSelect/index.vue'
import { checkStr, setPrintData } from '@/utils/judge'
var valiNumberPass = (rule, value, callback) => {
  setTimeout(() => {
    if (value == '' || value == undefined) {
      callback()
    } else if (isNaN(value)) {
      callback(new Error($i18n.t('mesProdOrderMaterial.validate')))
    } else {
      callback()
    }
  }, 100)
}
import {
  barcodePrintingList2,
  printTemplateInfo,
  mesProdBoxcode,
  baseCodeStrategy,
  getBoxCount,
  clearBoxcode,
  creatBoxCode, //生码
  printBarcode,
  getNextProcess,
  getQuantityById,
  printMaterial,
  getProcessList,
  getProcessListByTechnologyId
} from '@/api/barcodeprint/mesTrackingCardPrint'
import qs from 'qs'

let arrBarcodePrintingList2 = []
export default {
  name: 'barcodePrintingAddModel',
  components: { templateSelect },
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.form.resetForm()
        })
        this.barcodeInfo = {}
      }
    }
    // "dialogfrom.relaList": {
    //   handler: function (news, old) {
    //     this.$nextTick(() => {
    //       this.setQuantity();
    //     });
    //     // this.$nextTick(() => {
    //     //   this.setQuantity();
    //     // });
    //   },
    //   deep: true,
    // },
  },
  props: {
    title: {
      type: String,
      default: ''
    }
  },

  data() {
    let that = this
    return {
      loding: false,
      time: 0,
      defName: [],
      formConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: 'right',

        rules: {
          boxTotal: [{ validator: valiNumberPass, trigger: ['change', 'blur'] }],
          boxNumber: [{ validator: valiNumberPass, trigger: ['change', 'blur'] }],
          quantitys: [{ validator: valiNumberPass, trigger: ['change', 'blur'] }],
          pieceWeight: [{ validator: valiNumberPass, trigger: ['change', 'blur'] }],
          grossWeight: [{ validator: valiNumberPass, trigger: ['change', 'blur'] }]
        },
        formDesc: {
          orderCode: {
            type: 'input',
            label: $i18n.t('mesProdOrderMaterial.workOrderCode'),
            layout: 12,
            required: true,
            disabled: true
          },
          prodCode: {
            type: 'input',
            label: $i18n.t('mesProdOrderMaterial.code'),
            layout: 12,
            required: true,
            disabled: true
          },
          prodName: {
            type: 'input',
            label: $i18n.t('mesProdOrderMaterial.name'),
            layout: 12,
            required: true,
            disabled: true,
            on: {
              change: (data, e) => {
                //that.$message.warning("条码模板,");
                that.handleChange(data)
              }
            }
          },
          barcodePrintTemp: {
            type: 'input',
            label: $i18n.t('mesProdOrderMaterial.barcodePrintTemp'),
            layout: 12,
            // disabled: () => {
            //   return this.barcodeInfo.isCreateBarcode == 1 ? true : false;
            // },
            attrs: {
              readonly: true
            },
            required: true,
            slots: {
              append(h) {
                return (
                  <el-button
                    icon="el-icon-search"
                    onClick={() => {
                      that.$refs.templateSelect.show()
                    }}></el-button>
                )
              }
            },
            required: true,
            on: {
              change: (data, e) => {
                //that.$message.warning("条码模板,");
                that.handleChange(data)
                that.handleChangeQuantity()
              }
            }
          },
          lineName: {
            type: 'input',
            label: $i18n.t('common.lineName'),
            layout: 12,
            required: false,
            disabled: false
          },

          // workCellName: {
          //   type: "input",
          //   label: "工位名称",
          //   layout: 8,
          //   required: true,
          //   disabled: true,
          // },
          //bing
          productProcessCode: {
            type: 'select',
            label: $i18n.t('common.processName'),
            layout: 12,
            required: false,
            prop: {
              text: 'processName',
              value: 'processCode'
            },
            options: async (data) => {
              let { technologyId } = data

              let list = await getProcessListByTechnologyId({ technologyId })
              that.defName = list.data.result
              return list.data.result
            },
            on: {
              change: (data, e) => {
                //  _this.dialogfrom.productProcessName,
                //that.$message.warning("条码模板,");

                let obj = that.defName.find((ite) => ite.processCode == that.dialogfrom.productProcessCode)

                if (obj) {
                  that.dialogfrom.curProcessName = obj.processName
                }

                that.getBoxCount(data)
                that.handleChangeQuantity()
              }
            }
          },
          //接口返回字段为quantity  字段需要赋值其他 by bing
          // quantitys: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.totalCount"),
          //   layout: 8,
          //   //   required: true,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          nextProcessName: {
            type: 'input',
            label: $i18n.t('mesProdOrderMaterial.nextProcessName'),
            layout: 12,
            // required: true,
            // disabled: true,
            required: false,
            disabled: false
          }

          // equipmentCode: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.equipmentName"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // operatorBy: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.operatorBy"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // prodCode: {
          //   type: "input",
          //   label: "产品编码",
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // prodName: {
          //   type: "input",
          //   label: "产品名称",
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //     },
          //   },
          // },
          // equipmentCode: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.equipmentCode"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // // skGoodsCode: {
          // //   type: "input",
          // //   label: $i18n.t("mesProdOrderMaterial.skGoodsCode"),
          // //   layout: 8,
          // //   //  required: true,
          // //   // disabled: true,
          // //   on: {
          // //     change: (data, e) => {
          // //       //that.$message.warning("条码模板,");
          // //       that.handleChange(data)
          // //       that.handleChangeQuantity()
          // //     }
          // //   }
          // // },
          // materialChargeNumber: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.materialChargeNumber"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // pieceWeight: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.pieceWeight"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // grossWeight: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.grossWeight"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // finishDate: {
          //   type: "date",
          //   label: $i18n.t("mesProdOrderMaterial.finishDate"),
          //   layout: 8,
          //   attrs: {
          //     valueFormat: "yyyy-MM-dd",
          //   },
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // boxNumber: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.boxNumber"),
          //   layout: 8,
          //   // attrs: {
          //   //   min: 0,
          //   // },
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // boxTotal: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.boxTotal"),
          //   layout: 8,
          //   // attrs: {
          //   //   min: 0,
          //   // },
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // transferBillNumber: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.transferBillNumber"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
          // inspectionResult: {
          //   type: "input",
          //   label: $i18n.t("mesProdOrderMaterial.inspectionResult"),
          //   layout: 8,
          //   on: {
          //     change: (data, e) => {
          //       //that.$message.warning("条码模板,");
          //       that.handleChange(data);
          //       that.handleChangeQuantity();
          //     },
          //   },
          // },
        }
      },
      barcodeInfo: {},
      dialogfrom: {},
      visible: false,
      loading: false,
      list: [],
      print: {
        id: 'printArea'
      },
      defList: []
    }
  },
  methods: {
    //初始化
    async init(params) {
      this.defList = { ...params }
      this.dialogfrom = {
        ...params[0],
        barcodePrintTempCode: '',
        barcodePrintTemp: ''
      }
      this.barcodeInfo = params[0]
      //  await this.getBoxCount();
      //  await this.getQuantityById();

      this.visible = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.handleChange(params[0].printTemp)
        }, 1000)
      })
    },

    async getBoxCount() {
      let res = await getNextProcess({
        ...this.dialogfrom,
        curProcessCode: this.dialogfrom.productProcessCode
      })
      this.dialogfrom = {
        ...this.dialogfrom,
        ...res.data.result
        //   quantitys: res.data.result.quantity,
      }
    },
    async getQuantityById() {},
    // 计算表单总数量
    setQuantity() {
      this.$set(this.dialogfrom, 'quantitys', (this.dialogfrom.quantity = this.dialogfrom.relaList.reduce((prev, cur) => prev + cur.quantity, 0)))

      //console.log("12121", this.dialogfrom.quantity);
    },
    // 打印
    async printBoxcode() {
      this.$refs.form.validate().then(async (valid) => {
        // let res = await printMaterial({
        //   ...this.dialogfrom,
        //   printtype: 0,
        //   quantity: this.dialogfrom.quantitys,
        //   curProcessCode: this.dialogfrom.productProcessCode,
        // });
        let { barcodePrintTempCode, barcodePrintTemp } = this.dialogfrom;
        setPrintData(
          {
            code: barcodePrintTempCode,
            name: barcodePrintTemp,
            materialPrintType: '0',
            status: '0'
          },
          [this.dialogfrom]
        )
        this.$router.push('/splitPrint')

        this.visible = false
        this.$parent.refresh()
      })
    },
    async clearBoxcode() {
      try {
        let { value } = await this.$prompt($i18n.t('common.inputClearReason'), $i18n.t('common.tip'), {
          confirmButtonText: $i18n.t('common.ok'),
          cancelButtonText: $i18n.t('common.cancel'),
          inputValidator: (value) => {
            if (!value) {
              return $i18n.t('common.inputClearReason')
            }
          }
        })
        if (!value) {
          this.$message.warning($i18n.t("mesProdOrderMaterial.pleaseEnterTheReasonForTheClearBoxCode"))
          return
        }
        this.loding = true
        let res = await clearBoxcode({
          clearReason: value,
          orderCode: this.dialogfrom.orderCode
        })

        let deflt = this.dialogfrom.count
        this.dialogfrom.count = 999
        this.$nextTick(() => {
          this.dialogfrom.count = deflt
          this.getBoxCount()
          this.$set(this.barcodeInfo, 'isCreateBarcode', 0)
        })
      } finally {
        this.loding = false
      }
    },
    handleChangeQuantity(data) {
      // this.setQuantity();
      this.$set(this.barcodeInfo, 'values', {
        ...this.dialogfrom,
        quantity: this.dialogfrom.quantitys
      })
    },
    //条码模板选择
    handleChange(e) {
      if (arrBarcodePrintingList2.length == 0) return
      if (!this.dialogfrom.barcodePrintTemp) return
      let obj = arrBarcodePrintingList2.find((ite) => {
        return e == ite.templateName
      })
      if (!obj) return
      this.loading = true
      printTemplateInfo(obj.id)
        .then((res) => {
          this.time = new Date().getTime()
          this.barcodeInfo = {
            ...this.barcodeInfo,
            ...res.data.result,
            values: { ...this.dialogfrom, quantity: this.dialogfrom.quantitys }
          }
          // this.barcodeInfo.details.forEach(v => {
          //   v.componentHeight = '40'
          // })
        })
        .finally((res) => {
          this.loading = false
        })
    },
    //修改容量
    countChange(e) {
      let quantity = Number(this.dialogfrom.quantity)
      let printQuantity = Math.ceil(quantity / e)
      this.dialogfrom.printQuantity = printQuantity
    },
    //点击生码按钮
    creatBoxCode() {
      this.$refs.form.validate().then((valid) => {
        let { orderCode, count, barcodePrintTemp, boxCodeRule, printQuantity } = this.dialogfrom
        let data = {
          orderCode: orderCode, //'生产工单号',
          barcodePrintTemp: barcodePrintTemp, //'打印条码模板名称',
          boxCodeRule: boxCodeRule
        }

        this.$confirm($i18n.t('mesProdOrderMaterial.isCreatedTrackingCard'), $i18n.t('common.tip'), {
          confirmButtonText: $i18n.t('common.ok'),
          cancelButtonText: $i18n.t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.loding = true
          creatBoxCode(data)
            .then((res) => {
              if (res.data.success) {
                //  this.$refs.print.$refs.printing.$el.click();
                this.$message.success($i18n.t("mesProdOrderMaterial.createSuccess"))
                let deflt = this.dialogfrom.count
                this.dialogfrom.count = 999
                this.dialogfrom.id = res.data.result
                this.$nextTick(() => {
                  this.dialogfrom.count = deflt
                  this.getBoxCount()
                  this.$set(this.barcodeInfo, 'isCreateBarcode', 1)
                })
              }
              this.loding = false
            })
            .catch((err) => {
              this.loding = false
            })
        })
      })
    },

    clearDialog() {
      this.visible = false
      this.$emit('refreshList')
    },
    //点击打印按钮
    handleRequest() {
      this.$refs.form.handleSubmitForm()
      this.$refs.form.validate().then((valid) => {
        let data = {
          isPrint: 0,
          orderCode: this.dialogfrom.orderCode //'生产工单号',
        }
        mesProdBoxcode(data).then((res) => {
          if (res.data.success) {
            let list = res.data.result,
              info = this.barcodeInfo,
              infoList = []
            if (Array.isArray(list) && list.length > 0) {
              list.forEach((item) => {
                infoList.push(item)
              })
            }
            delete info.values
            info.values = infoList
            localStorage.splitPrint = JSON.stringify(info)

            this.clearDialog()
            window.open('/mom/component/mes/splitPrint?type=1')
          }
        })
      })

      // barcodePrintingAdd(data)
      //   .then((res) => {
      //     if (res.data.success) {
      //       this.$refs.print.$refs.printing.$el.click();
      //     }
      //     this.$emit("refreshList");
      //   })
      //   .catch((err) => {
      //     console.log("查询失败", err);
      //   });
    }
  }
}
</script>

<style lang="scss" scoped>
.print-model {
  .pack {
    padding: 20px;
    padding-top: 0px;
  }
  #printArea {
    position: relative;
  }
  .dialog-footer {
    padding-top: 20px;
    display: flex;
    justify-content: end;
  }
  .dis-none {
    display: none;
  }
}
</style>
